package com.ruoyi.grade.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.grade.domain.Gradetemplate;
import com.ruoyi.stuinfo.domain.AcademicInfo;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.grade.domain.Grade;
import com.ruoyi.grade.service.IGradeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 成绩详情Controller
 *
 * @author LinBei
 * @date 2025-05-15
 */
@RestController
@RequestMapping("/grade/grade")
public class GradeController extends BaseController
{
    @Autowired
    private IGradeService gradeService;

    /**
     * 查询成绩详情列表
     */
    @PreAuthorize("@ss.hasPermi('grade:grade:list')")
    @GetMapping("/list")
    public TableDataInfo list(Grade grade)
    {
        String teacherId=getUsername();
        boolean hasH = teacherId.contains("H");
        boolean hasX = teacherId.contains("X");
        if("admin".equals(teacherId))
        {
            //管理员
            startPage();
            List<Grade> list = gradeService.selectGradeList(grade);
            return getDataTable(list);
        }
        else if(hasH)
        {
            //教师
            teacherId=teacherId.replace("H", "");
            startPage();
            List<Grade> list = gradeService.selectGradeList_handteacher(teacherId);
            return getDataTable(list);
        }
        else if(hasX)
        {
            //系主任
            teacherId=teacherId.replace("X", "");
            startPage();
            List<Grade> list = gradeService.selectGradeList_Xiteacher(teacherId);
            return getDataTable(list);
        }
        else
        {
            //教师
            startPage();
            List<Grade> list = gradeService.selectGradeList_teacher(teacherId);
            return getDataTable(list);
        }
    }

    /**
     * 导出成绩详情列表
     */
    @PreAuthorize("@ss.hasPermi('grade:grade:export')")
    @Log(title = "成绩详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Grade grade)
    {
        String teacherId=getUsername();
        boolean hasH = teacherId.contains("H");
        boolean hasX = teacherId.contains("X");
        if("admin".equals(teacherId))
        {
            //管理员
            List<Grade> list = gradeService.selectGradeList(grade);
            ExcelUtil<Grade> util = new ExcelUtil<Grade>(Grade.class);
            util.exportExcel(response, list, "成绩详情数据");
        }
        else if(hasH)
        {
            //班主任
            teacherId=teacherId.replace("H", "");
            List<Grade> list = gradeService.selectGradeList_handteacher(teacherId);
            ExcelUtil<Grade> util = new ExcelUtil<Grade>(Grade.class);
            util.exportExcel(response, list, "成绩详情数据");
        }
        else if(hasX)
        {
            //系主任
            teacherId=teacherId.replace("X", "");
            List<Grade> list = gradeService.selectGradeList_Xiteacher(teacherId);
            ExcelUtil<Grade> util = new ExcelUtil<Grade>(Grade.class);
            util.exportExcel(response, list, "成绩详情数据");
        }
        else
        {
            //教师
            List<Grade> list = gradeService.selectGradeList_teacher(teacherId);
            ExcelUtil<Grade> util = new ExcelUtil<Grade>(Grade.class);
            util.exportExcel(response, list, "成绩详情数据");
        }
    }

    /**
     * 获取成绩详情详细信息
     */
    @PreAuthorize("@ss.hasPermi('grade:grade:query')")
    @GetMapping(value = "/{gradeId}")
    public AjaxResult getInfo(@PathVariable("gradeId") Long gradeId)
    {
        return success(gradeService.selectGradeByGradeId(gradeId));
    }

    /**
     * 新增成绩详情
     */
    @PreAuthorize("@ss.hasPermi('grade:grade:add')")
    @Log(title = "成绩详情", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Grade grade)
    {
        int rows = gradeService.insertGrade(grade);
        if (rows > 0) {
            // 调用存储过程
            gradeService.calculateClassRanking();
        }
        return toAjax(rows);
    }

    /**
     * 修改成绩详情
     */
    @PreAuthorize("@ss.hasPermi('grade:grade:edit')")
    @Log(title = "成绩详情", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Grade grade)
    {
        int rows = gradeService.updateGrade(grade);
        if (rows > 0) {
            // 调用存储过程
            gradeService.calculateClassRanking();
        }
        return toAjax(rows);
    }
    /**
     * 删除成绩详情
     */
    @PreAuthorize("@ss.hasPermi('grade:grade:remove')")
    @Log(title = "成绩详情", businessType = BusinessType.DELETE)
	@DeleteMapping("/{gradeIds}")
    public AjaxResult remove(@PathVariable Long[] gradeIds)
    {
        int rows = gradeService.deleteGradeByGradeIds(gradeIds);
        if (rows > 0) {
            // 调用存储过程
            gradeService.calculateClassRanking();
        }
        return toAjax(rows);
    }


    /**
     * 获取成绩分布统计结果（简化版）
     */
    @GetMapping("/distribution")
    public ResponseEntity<Map<String, Integer>> getGradeDistribution() {
        Map<String, Integer> distribution = gradeService.getGradeDistribution();
        return ResponseEntity.ok(distribution);
    }
    //模板
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {

        ExcelUtil<Gradetemplate> util = new ExcelUtil<Gradetemplate>(Gradetemplate.class);
        util.importTemplateExcel(response, "用户数据");
    }

    @PreAuthorize("@ss.hasPermi('grade:grade:adds')")
    @Log(title = "成绩详情", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult excelImport(MultipartFile file) throws Exception {
        ExcelUtil<Grade> util = new ExcelUtil<Grade>(Grade.class);
        List<Grade> GradeList = util.importEasyExcel(file.getInputStream());
        return toAjax(gradeService.insertGrades(GradeList));
    }

    /**
     * 获取成绩分布详细信息（包含分段名称和范围）
     */
//    @GetMapping("/distribution/details")
//    public ResponseEntity<List<Map<String, Object>>> getGradeDistributionDetails() {
//        List<Map<String, Object>> details = gradeService.getGradeDistributionDetails();
//        return ResponseEntity.ok(details);
//    }
}
